package com.test;

import java.util.ArrayList;
import java.util.Random;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;

public class dynamicList extends ListActivity{
	public PhotoAdapter myAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.dynamiclist_view);
		getListView().setEmptyView(findViewById(R.id.empty));
		myAdapter = new PhotoAdapter(this);
		setListAdapter(myAdapter);
		
		Button clear = (Button) findViewById(R.id.clear);
		clear.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				myAdapter.clearPhotos();
			}
		});
		
		Button add = (Button) findViewById(R.id.add);
		add.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				myAdapter.addPhotos();
			}
		});
	}

	public class PhotoAdapter extends BaseAdapter {
		private ImageDownloader loader;
		private ArrayList<Drawable> photos = new ArrayList<Drawable>();
		
		public Context mContext;
		
		public PhotoAdapter(Context c) {
			mContext = c;
			loader = new ImageDownloader();
		}
		
		public void clearPhotos() {
			photos.clear();
			notifyDataSetChanged();
		}
		
		public String randomString() {
			Random r = new Random();
			String ret = "";
			for (int i=0; i<7; i++)
				ret = ret + String.valueOf(r.nextInt(9)+1);
			return ret;
		}
		
		public void addPhotos() {
			String imageUrl = "http://img3.douban.com/mpic/s" + randomString() + ".jpg";
			Drawable d = loader.loadDrawable(imageUrl, new ImageCallback() {
				public void imageLoaded(Drawable imageDrawable, String imageUrl) {
					photos.add(imageDrawable);
					notifyDataSetChanged();
				}
			});
			if (d != null) {
				photos.add(d);
				notifyDataSetChanged();
			}
        }
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ImageView iv = new ImageView(mContext);
			iv.setImageDrawable(photos.get(position));
			iv.setAdjustViewBounds(true);
			iv.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			return iv;
		}

		@Override
		public int getCount() {
			return photos.size();
		}

		@Override
		public Object getItem(int arg0) {
			return this.photos.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
	}
}
